<template>
    <div class="container">
        <!--背景图  -->
        <img src="https://dev-mai8mall.oss-cn-hangzhou.aliyuncs.com/water/WechatIMG14924.png" class="container-bg">
        <!-- 主要内容 -->
        <div class="container-m">
            <div class="container-m-chen">
              <!-- 注意事项 -->
              <p class="container-m-t" >注：填写信息中打<span style="color:#ff0000;">※</span>号的为必填项，其余为选填项。</p>
              
              <!-- 搜索框 -->
              <div  class="container-m-inp" flex="cross:center main:justify">
                  <div
                    v-if="!mapInfo" 
                    class="container-m-inp-d" 
                    flex="cross:center">请输入要搜索的地点信息<span style="color:#ff0000;">※</span></div>
                  <div 
                    v-else
                    class="container-m-inp-d" 
                    >{{mapInfo.addr+mapInfo.name}}</div>
                  <img src="../../images/search.png" class="container-m-inp-i">
                  <a :href="href" @click="toSelectAddress" style="width:100%;height:100%;position:absolute;left:0;bottom:0; z-index:100;"></a>
              </div>
              <!-- 输入电话 -->
              <div class="container-m-inp">
                  <input 
                    class="container-m-inp-in"  
                    type="number"
                    v-model="pageData.phoneNum"
                    ref="phoneNum"
                    @blur="inpuBlur"
                    v-show="!pageData.phoneMask"
                    :placeholder="pageData.phoneMask&&pageData.phoneNum == ''?'':'请输入联系电话'">
                  <p 
                    class="container-m-inp-tx" 
                    flex="cross:center main:center"
                    v-if="pageData.phoneMask"
                    @touchstart="showInput"
                    @click="inptFous">联系电话（必填）<span style="color:#ff0000;">※</span></p>
              </div>
              <!-- 输入信息 -->
              <div class="container-m-inp" style="height:1.57rem;">
                  <textarea  
                    class="container-m-inp-txt"
                    v-model="pageData.dec" 
                    name="text"
                    ref="textarea"
                    v-show="!pageData.decMask"
                    :placeholder="pageData.decMask&&pageData.dec == ''?'':'请详细描述易涝点的相关信息'" 
                    @blur="textBlur"></textarea>
                  <p 
                    class="container-m-inp-tx" 
                    flex="cross:center main:center"
                    v-if="pageData.decMask"
                    @touchstart="showTextFous"
                    @click="textFous">请详细描述易涝点的相关信息……</p>
              </div>
              <!-- 现场图 -->
              <div class="container-m-b" flex-wrap flex="cross:center main:justify">
                  <div 
                    class="container-m-b-r" 
                    style="position:relative;"
                    flex="cross:center main:center dir:top"
                    v-for="(item, index) in pageData.imgs" :key="index">
                    <div v-if="!item.state"   flex="cross:center main:center dir:top">
                      <img src="../../images/upload_bg.png" class="container-m-b-r-i">
                      <span style="font-size:.12rem;">（易涝点现场图片）</span>
                      <upload 
                          :index="index"
                          :id="item.id"
                          :imgArea="1"
                          @statusFor="getUpladImg">
                      </upload>
                    </div>
                    <div style="width:100%;height:100%;position:relative;" v-else>
                        <img :src="item.imgObj.imagePath" style="width:100%;height:100%;object-fit:cover;border-radius: .1rem;">
                        <img src="../../images/close.png" class="dleI" @click="delImg(index)">
                    </div>
                    
                  </div>
              </div>
            
              <!-- 规则 -->
              <div flex="cross:center main:justify " class="ruleBtn_p" style="margin-top:.06rem;">
                <div></div>
                <div class="ruleBtn" flex="cross:center main:center dir:top" @click="openRelu">
                    <img src="../../images/rule.png" style="width:.23rem;height:.27rem;">
                    规则
                </div>
              </div>
            
              <!-- 提交 -->
              <div class="saveBtn" flex="cross:center main:center" @click="saveConten">提交</div>
          </div>
        </div>
          <!-- 活动规则 -->
        <div class="maskPop" v-if="reluState">
            <div class="maskPop-r">
                <div class="maskPop-r-t" flex="cross:center">
                    活动时间
                </div>
                <div class="maskPop-r-d"  flex="cross:center">2019.09.05—2019.09.11</div>
                <div class="maskPop-r-t" flex="cross:center" style="margin-bottom:.04rem;">
                    活动规则
                </div>
                <div class="maskPop-r-tx"  flex="cross:center">
                    1.用户通过微信公众号软文参与活动。
                </div>
                <div class="maskPop-r-tx"  flex="cross:center">
                    2.用户在活动界面填写上传关于易涝点的详细信息和图片。
                </div>
                <div class="maskPop-r-tx"  flex="cross:center">
                   3.活动结束之后，我们将选取推荐最集中的前100个易涝点，利用物联网技术设备进行水浸实时监控。易涝点被抽取的用户将获得我们提供的免费洗车券一份。
                </div>
                <div class="maskPop-r-tx"  flex="cross:center">
                   4.活动结束后，我们将在公众号软文中公布被选取提交易涝点信息的用户，我们将对着100名用户发放奖品，奖品将在活动结束后的24小时内以微信消息的形式发放至获奖用户微信。  
                </div>
                <img src="../../images/close.png" class="maskPop-r-c" @click="closeRule">
            </div>
        </div>
        <!-- 提交成功 -->
        <div class="maskPop" v-if="sucState">
            <div class="maskPop-s">
              <div class="maskPop-s-tit" flex="cross:center main:center">提交成功啦~</div>
              <div class="maskPop-s-dec"  flex="cross:center">注：我们将在活动结束之后选取推荐最集中的前100个易涝点，利用物联网技术设备进行水浸实验并实时监控。易涝点被抽取的用户将获得我们提供的免费洗车券一份。</div>
              <img src="../../images/close.png" class="maskPop-s-c" @click="closeSuc">
            </div>
           
        </div>
       <!-- 消息弹窗 -->
       <div class="infoBox" flex="cross:center main:center" v-show="messState">{{message}}</div>
    </div>
 
</template>

<script>
import { getWx,saveWater } from '../../api/apis/home.js';
import wxUplod from '../../components/wxUpload.vue'
import upload from '../../components/uploadImg.vue'
import { setTimeout } from 'timers';
import wx from 'weixin-js-sdk'
export default {
  name: 'home',
  data(){
    return{
      pageData:{
        // 输入框遮罩
        phoneMask:true,
        // 手机号
        phoneNum:'',
        //  描述遮罩
        decMask:true,
        // 描述
        dec:'',
        // 易涝点图片列表
        imgs:[
            {
              id:'one',
              imgObj:null,
              state:false
            },
            {
              id:'tow',
              imgObj:null,
              state:false
            },
            {
              id:'three',
              imgObj:null,
              state:false
            },
            {
              id:'four',
              imgObj:null,
              state:false
            }
        ],
     
      },
      // 活动规则
      reluState:false,
      // 提交成功
      sucState:false,
      // 信息提示框
      messState:false,
      message:null,
    
      // 防止再次提交
      outIng:false,
      // 提交状态
      saveState:false,
      mapInfo:null,
      windowH:0,
      href: 'http://apis.map.qq.com/tools/locpicker?search=1&type=0&key=OGIBZ-HWW3J-ALPF7-FQNH5-ST2MS-ATFPF&referer=myapp',
      openid:null
      

    }
  },
 
  components:{
      upload,
  },
  created(){
      this.getWxConfig();
      if(this.getUrlSearch("addr")){
          this.mapInfo = {
              addr:this.getUrlSearch("addr"),
              name:this.getUrlSearch("name") == '我的位置'?'':this.getUrlSearch("name"),
              latng:this.getUrlSearch("latng"),
          }
      }else{
        this.mapInfo = null;
      }
      if(this.getUrlSearch("openid")){
        this.openid = this.getUrlSearch("openid");
        window.sessionStorage.setItem('openid',this.getUrlSearch("openid"));
      }  
    
  },
  
  mounted(){
     if(!this.mapInfo){
        window.sessionStorage.removeItem("pageData");　
      }
      let pageData = window.sessionStorage.getItem('pageData');
      if(pageData){
          this.pageData = JSON.parse(pageData);
          console.log('////')
          console.log(this.pageData)
      }
      let containerM = document.getElementsByClassName('container-m')[0];
      let containerC = document.getElementsByClassName('container-m-chen')[0];
      console.dir(containerM)
      let containerMH = containerM.clientHeight;
      containerC.style.minHeight = (containerMH+20)+'px'
      //动态设置高度 
    //  let windowH = window.screen.height - 70;
    //  let container = document.getElementsByClassName('container')[0];
    //  this.windowH = windowH;
    //  container.style.height = windowH+'px'; 
  },
  methods:{
  
    // 关闭成功弹窗
    closeSuc(){
       this.sucState = false;
       this.saveState = true;
       window.scroll(0,0);
      
    },
    openRelu(){
      this.reluState = true;
      let containerM = document.getElementsByClassName('container-m')[0];
      containerM.scrollTop = 0;
    },
    // 关闭规则弹窗 
    closeRule(){
      this.reluState = false;
      window.scroll(0,0);
    },
    // 获取浏览器参数
    getUrlSearch(name) {
      // 未传参，返回空
      if (!name) return null;
      // 查询参数：先通过search取值，如果取不到就通过hash来取
      var after = window.location.search;
      after = after.substr(1) || window.location.hash.split('?')[1];
      // 地址栏URL没有查询参数，返回空
      if (!after) return null;
      // 如果查询参数中没有"name"，返回空
      if (after.indexOf(name) === -1) return null;
    
      var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
      // 当地址栏参数存在中文时，需要解码，不然会乱码
      var r = decodeURI(after).match(reg);
      // 如果url中"name"没有值，返回空
      if (!r) return null;
    
      return r[2];
    },
    // 存储数据
    setStore(){
       window.sessionStorage.setItem('pageData',JSON.stringify(this.pageData));
    },
    // 页面跳转
    toSelectAddress() {
      this.setStore();
      let href = window.location.href;
      let urlArr = href.split('?');
      if( this.mapInfo){
          this.href = this.href + `&coord=${this.mapInfo.latng}&backurl=${urlArr[0]}` 
      }else{
         this.href = this.href + `&backurl=${urlArr[0]}` 
      }
     
    },
    // 图片删除 
    delImg(index){
      this.pageData.imgs[index].imgObj = null;
      this.pageData.imgs[index].state = false;
    },
     //保存
     saveConten(){
       if(this.saveState){
          this.openState('您已经提交！');
          return;
       }
       if(!this.mapInfo){
          this.openState('地点不能为空！');
          return;
       }
       if(this.pageData.phoneNum == ''){
          this.openState('手机号不能为空！');
          return;
       }
       if(this.pageData.phoneNum .length != 11){
          this.openState('手机号格式不正确！');
          return;
       }
       if(!(/^1[3456789]\d{9}$/.test(this.pageData.phoneNum))){ 
          this.openState('手机号格式不正确！');
          return;
        }
        if(this.outIng){
         return;
       }
       this.outIng = true;
       let latlng = this.mapInfo.latng.split(',');
        let obj ={
            address:this.mapInfo.addr+this.mapInfo.name,
            latitude:latlng[0],
            longitude:latlng[1],
            phoneNo:this.pageData.phoneNum
        }
        if(this.pageData.dec != ''){
           obj.content = this.pageData.dec;
        }
        var imagePaths = [];
        for(var i = 0,len = this.pageData.imgs.length;i<len;i++){
            var item = this.pageData.imgs[i];
            if(item.state && item.imgObj){
              imagePaths.push(item.imgObj.key);
            }
        }
        if(imagePaths.length != 0){
           obj.images = imagePaths;
        }
        let openid =  window.sessionStorage.getItem('openid');
        if(openid){
           obj.openId = openid;
        }
        if(this.openid){
          obj.openId = this.openid;
        }
       
        
        saveWater(obj).then(res=>{
          const {success,message,result} = res
          if(success){
              this.sucState = true;
              window.sessionStorage.removeItem("pageData");
              this.mapInfo = null;　
              this.pageData = {
                // 输入框遮罩
                phoneMask:true,
                // 手机号
                phoneNum:'',
                //  描述遮罩
                decMask:true,
                // 描述
                dec:'',
                // 易涝点图片列表
                imgs:[
                    {
                      id:'one',
                      imgObj:null,
                      state:false
                    },
                    {
                      id:'tow',
                      imgObj:null,
                      state:false
                    },
                    {
                      id:'three',
                      imgObj:null,
                      state:false
                    },
                    {
                      id:'four',
                      imgObj:null,
                      state:false
                    }
                ]
              }
          }else{
             this.openState(message);
          }
          this.outIng = false;
        })
       
      
     },
     openState(message){
        this.messState = true;
        this.message = message;
        setTimeout(()=>{
          this.messState = false;
        },2000)
     },
     // 获取上传图片数据
      getUpladImg(result,index) {
          if (result) {
            this.pageData.imgs[index].imgObj =  result;
            this.pageData.imgs[index].state =  true;
          }
      },
      //获取微信
      getWxConfig(){
        let href = window.location.href;
        if(href.indexOf('?') != -1){
          href = href.split("?")[0];
        }
        let params = {
          shareUrl:href
        }
        getWx(params).then(res=>{
          const {success,result} = res
          if(success){
              wx.config({
                  debug: false,////生产环境需要关闭debug模式
                  appId: result.appId,//appId通过微信服务号后台查看
                  timestamp: result.timestamp,//生成签名的时间戳
                  nonceStr: result.nonceStr,//生成签名的随机字符串
                  signature: result.signature,//签名
                  jsApiList: [//需要调用的JS接口列表
                      'checkJsApi',//判断当前客户端版本是否支持指定JS接口
                      'onMenuShareTimeline',//分享给好友
                      'onMenuShareAppMessage',//分享到朋友圈
                      'hideMenuItems',//批量隐藏微信功能按钮
                  ]
              });
              wx.ready(function () {
                  var link = "https://h5.iliujia.com/picc_activity/share";
                  // 批量隐藏微信功能按钮
                  wx.hideMenuItems({
                      menuList: [
                          "menuItem:share:qq", //分享到QQ
                          "menuItem:share:weiboApp",//分享到微博
                          "menuItem:share:QZone",//分享到QQ空间
                      ], // 要隐藏的菜单项
                  });
                  //分享朋友圈
                  wx.onMenuShareTimeline({
                      title:result.descs, // 分享标题
                      link: link,
                      imgUrl:result.logo,// 自定义图标
                      trigger: function (res) {
                          // 不要尝试在trigger中使用ajax异步请求修改本次分享的内容，因为客户端分享操作是一个同步操作，这时候使用ajax的回包会还没有返回.
                          //alert('click shared');
                      },
                      success: function (res) {
                          //alert('shared success');
                          //some thing you should do
                      },
                      cancel: function (res) {
                          //alert('shared cancle');
                      },
                      fail: function (res) {
                          //alert(JSON.stringify(res));
                      }
                  });
                  //分享给好友
                  wx.onMenuShareAppMessage({
                      title: result.descs, // 分享标题
                      desc:  result.title,// 分享描述
                      link: link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                      imgUrl: result.logo, // 自定义图标
                      type: 'link', // 分享类型,music、video或link，不填默认为link
                      dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                      success: function () {
                          // 用户确认分享后执行的回调函数
                      },
                      cancel: function () {
                          // 用户取消分享后执行的回调函数
                      }
                  });
                  wx.error(function (res) {
                      // alert(res.errMsg);
                  });
              });
          }
        })
      },
      showTextFous(){
         this.pageData.decMask = false;
      },
      //  输入框获取信息
      textFous(){
          let text = this.$refs.textarea;
          text.focus();
      },
      //  输入框失去焦点
      textBlur(){
         if(this.pageData.dec == ''){
            this.pageData.decMask = true;
          }
          document.body.scrollTop = 0;
	        document.documentElement.scrollTop = 0;
      },
      showInput(){
        this.pageData.phoneMask = false;
      },
      // 使获取手机号框 获取焦点
      inptFous(){
          let input = this.$refs.phoneNum;
          input.focus();
      },
      // 输入框失去焦点
      inpuBlur(){
        if(this.pageData.phoneNum == ''){
          this.pageData.phoneMask = true;
        }
        document.body.scrollTop = 0;
	      document.documentElement.scrollTop = 0;
      }
     
     
     
  }

}
</script>
<style scoped lang="scss">
.container{
    width: 100%;
    height:100%;
    background-color: #52738c;
    position: relative;
    &-bg{
        width: 100%;
        height: 114%;
        object-fit: cover;
        position: absolute;
        left: 0;
        top: -14%;
        z-index: 100;
    }
    &-m{
        width: 100%;
        height: 100%;
        padding:.19rem .12rem 0;
        position: relative;
        left: 50%;
        top: 0;
        transform: translateX(-50%);
        z-index: 1000;
        overflow-y: auto;
        -webkit-overflow-scrolling: touch;   
        &-t{
          width: 100%;
          height: .13rem;
          line-height: .13rem;
          font-size: .13rem;
          color: #fff;
          margin-bottom:.12rem;
        }
        &-inp{
          width: 100%;
          height: .45rem;
          border-radius: .1rem;
          background-color: rgba(255,255,255,.9);
          padding:0 .14rem 0 .22rem;
          box-sizing: border-box;
          margin-bottom: .19rem;
          position:relative;
          &-d{
            width: 90%;
            height: .28rem;
            line-height: .28rem;
            font-size: .12rem;
            color: #757575;
            padding-right: .12rem;
            box-sizing: border-box;
            border-right: 1px solid #757575;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          &-i{
             width:.16rem;
             height: .16rem;
          }
          &-in,&-tx,&-txt{
            width: 100%;
            height: 100%;
            font-size: .12rem;
            color: #757575;
            background-color: rgba(255,255,255,0);
          }
          &-tx{
            width: 100%;
            height: 100%;
            color: #757575;
          

          }
          &-txt{
              padding: .12rem 0;
          }
        
        }
        &-b{
          width: 100%;
          &-r{
            width: 1.72rem;
            height: .94rem;
            font-size: .12rem;
            color:#757575;
            margin-bottom: .04rem;
            border-radius: .1rem;
            background-color: rgba(255,255,255,.9);
            &-i{
              width: .52rem;
              height: .46rem;
              margin-bottom: .04rem;
            }
          }
        }
        .ruleBtn{
          width: .54rem;
          height: .54rem;
          background-color: #fc7f41;
          font-size: .13rem;
          font-weight: 600;
          color: #fefefe;
          border-radius: 50%;
        }
        .ruleBtn_p{
         
        }
        .saveBtn{
          width: 1.19rem;
          height: .44rem;
          font-size: .2rem;
          color: #fefefe;
          font-weight: 600;
          background-color: #fc7f41;
          border-radius: .1rem;
          margin:.12rem auto 1rem;
          
          
        }
        .maskss{
          position: fixed;
          right: 0rem;
          bottom:.66rem;
           z-index: 100;

          position: fixed;
          left: 50%;
          transform: translateX(-50%);
          bottom:.08rem;
          z-index: 100;
        }
       
        
    }
    // 弹窗
    .maskPop{
        width: 100%;
        height: 100%;
        position: fixed;
        left: 0;
        top: 0;
        background-color: rgba(0,0,0,.7);
        z-index: 4000;
       
        &-r, &-s{
          width: 3.24rem;
          height: 3.95rem;
          position: absolute;
          left: 50%;
          top: 40%;
          transform: translate(-50%,-50%);
          background: url('../../images/rulePop.png') no-repeat center;
          background-size: cover;
          padding-top: .64rem;
          box-sizing: border-box;
          &-c{
            width: .4rem;
            height: .4rem;
            position: absolute;
            left: 50%;
            transform: translateX(-50%);
            bottom:-.6rem;
          }
          &-t{
            width: 1.12rem;
            height: .32rem;
            background: url('../../images/border.png') no-repeat center;
            background-size: cover;
            font-size: .18rem;
            color: #ffffff;
            padding-left: .09rem;
            box-sizing: border-box;
          }
          &-d{
            width: 100%;
            height: .35rem;
            font-size: .15rem;
            color:#000000;
            padding-left: .09rem;
          }
          &-tx{
            width: 100%;
            line-height:.19rem;
            font-size: .13rem;
            color:#000000;
            padding: 0 .09rem;
            box-sizing: border-box;
          }
        }
        &-s{
          width: 3.02rem;
          background: url('../../images/sucPop.png') no-repeat center;
          background-size: cover;
          padding-top: 2.25rem;
          top: 40%;
          &-c{
            width: .4rem;
            height: .4rem;
            position: absolute;
            left: 50%;
            transform: translateX(-50%);
            bottom:-.4rem;
          }
          &-tit{
            font-size: .24rem;
            color:#fc7f41;
            margin-bottom: .25rem;
          }
          &-dec{
            width: 100%;
            font-size: .11rem;
            color: #fb7f44;
            line-height: 1.2;
            padding: 0 .36rem;
            text-align: center;
          }
        }
      
    }
    .infoBox{
       min-width: 1.6rem;
       height: .4rem;
       padding: .12rem;
       box-sizing: border-box;
       background-color: rgba(0,0,0,.8);
       font-size: .14rem;
       color: #fff;
       position: fixed;
       left: 50%;
       top:50%;
       z-index: 9999;
       transform: translate(-50%,-50%);
       border-radius: .1rem;
    }
    .dleI{
      width: .2rem;
      height: .2rem;
      position: absolute;
      right:-.1rem;
      top:-.1rem;
    }
    
}
</style>